package com.monitor.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.monitor.dao.SmsMotionDao;
import com.monitor.po.SmsMotion;

@SuppressWarnings("unchecked")
public class SmsMotionDaoImpl implements SmsMotionDao {
	private SessionFactory sessionFactory;

	@Override
	public int delelteMotion(Long id) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("delete from SmsMotion s where s.id=:id").setLong("id", id).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured while excuting delelteMotion");
		}
	}

	@Override
	public List<SmsMotion> getMotionsByIds(long[] ids) throws Exception {
		try {
			StringBuffer sql = new StringBuffer("from SmsMotion s where ");
			int length = ids.length;
			for (int i = 0; i < length; i++) {
				sql.append("s.id=?");
				if (i != length - 1) {
					sql.append(" or ");
				}
			}
			Query query = sessionFactory.getCurrentSession().createQuery(sql.toString());
			for (int i = 0; i < length; i++) {
				query.setLong(i, ids[i]);
			}
			return query.list();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured while excuting getMotionsByIds");
		}
	}

	@Override
	public List<SmsMotion> getSmsMotions(long uid) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("from SmsMotion s where s.ownerUid=:uid").setLong("uid", uid).list();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured while excuting getSmsMotions");
		}
	}

	@Override
	public void addSmsMotion(SmsMotion motion) throws Exception {
		try {
			sessionFactory.getCurrentSession().persist(motion);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured while excuting addSmsMotion");
		}
	}

	@Override
	public void deleteSmsMotionByUid(long uid) throws Exception {
		try {
			sessionFactory.getCurrentSession().createQuery("delete from SmsMotion s where s.ownerUid=:uid").setLong("uid", uid).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured while excuting deleteSmsMotionByUid");
		}
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
